/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.angholt.bookproject;

import edu.chl.angholt.bookproject.db.Database;
import edu.chl.angholt.bookproject.db.entity.Author;
import edu.chl.angholt.bookproject.db.entity.Book;
import edu.chl.angholt.bookproject.db.entity.User;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Patric
 */
@WebServlet(name = "DisplayServlet", urlPatterns = {"/DisplayServlet"})
public class DisplayServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String type = request.getParameter("type");
            if (type != null) {

                if (type.equals("book")) {     //User has clicked a book title, we need to get information for that book
                    Book book = null;
                    String id = request.getParameter("id");
                    String title = request.getParameter("title");
                    if (id != null) {           //Can find book either by id...
                        book = Database.getBookController().findEntity(Long.parseLong(id));
                    } else if (title != null) { //... or title
                        book = Database.getBookController().findBook(title);
                    }
                    if (book != null) {         //Check that we actually found a book
                        boolean read = false;
                        HttpSession ses = request.getSession(false);
                        if (ses != null) {      //If a session exists we get the associated user and checks if he has read the book
                            User user = (User) ses.getAttribute("user");
                            if (user != null) { //Dubel check that the user exixts shout alwas pass
                                read = Database.getUserController().haveRead(user, book);
                            }
                        }
                        request.setAttribute("read", read);
                        request.setAttribute("book", book);
                        request.getRequestDispatcher("/book.jspx").forward(request, response);      //Forward to the bookinfo page with the new paramaters
                    } else {                    //Could not find the book
                        request.getRequestDispatcher("/404.jspx").forward(request, response);
                    }

                } else if (type.equals("author")) {         //User has clicked an author name, we need to get information for that author
                    Author author = null;
                    String id = request.getParameter("id");
                    String name = request.getParameter("name");
                    if (id != null) {                   //Can get author either by id...
                        author = Database.getAuthorController().findEntity(Long.parseLong(id));
                    } else if (name != null) {          //... or by name
                        author = Database.getAuthorController().findAuthor(name);
                    }
                    if (author != null) {               //Author found? If so get his information and add those parameters before forwarding
                        List<Book> books = Database.getAuthorController().getBooksByAuthor(author.getName());
                        request.setAttribute("books", books);
                        request.setAttribute("author", author);
                        request.getRequestDispatcher("/author.jspx").forward(request, response);
                    } else {    //No author found                        
                        request.getRequestDispatcher("/404.jspx").forward(request, response);
                    }

                } else if (type.equals("search")) {      //Search button clicked
                    String name = request.getParameter("name");
                    String title = request.getParameter("title");
                    List<Author> authors = null;
                    List<Book> books = null;
                    if (title != null) {        //Search by title (can also do both)
                        books = Database.getBookController().findBookLike(title);
                    }
                    if (name != null) {         //Search by author (can also do both)
                        authors = Database.getAuthorController().findAuthorLike(name);
                    }

                    //Set the attributes found and forward to search result page
                    request.setAttribute("books", books);
                    request.setAttribute("authors", authors);
                    request.getRequestDispatcher("/search.jspx").forward(request, response);
                } else if (type.equals("browseBooks")) { //get list of all books for brows 
                    List<Book> list = Database.getBookController().findEntities();
                    request.setAttribute("books", list);
                    request.getRequestDispatcher("/browseBooks.jspx").forward(request, response);
                } else if (type.equals("browseAuthors")) { //get list of all authors for brows
                    List<Author> list = Database.getAuthorController().findEntities();
                    request.setAttribute("authors", list);
                    request.getRequestDispatcher("/browseAuthors.jspx").forward(request, response);
                } else {   //No matching function for "type" found
                    request.getRequestDispatcher("/404.jspx").forward(request, response);
                }
            } else {    //"type" parameter is null
                request.getRequestDispatcher("/404.jspx").forward(request, response);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            request.getRequestDispatcher("/404.jspx").forward(request, response);
        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
